import type { App, Directive } from 'vue';
import { useAuth } from '@/hooks/business/auth';

export default function setupPermissionDirective(app: App) {
  const { hasAuth } = useAuth();

  function updateElVisible(el: HTMLElement, permission: string | string[]) {

    if (!permission) {
      // throw new Error(`need roles: like v-permission="xxx:xx", v-permission="['xxx:xxx', 'yyy:yyy]"`);
			return;
    }
    if (!hasAuth(permission)) {
      el.parentElement?.removeChild(el);
    }
  }

  const permissionDirective: Directive<HTMLElement, string | string[]> = {
    mounted(el, binding) {
      updateElVisible(el, binding.value);
    },
    beforeUpdate(el, binding) {
      updateElVisible(el, binding.value);
    }
  };

  app.directive('permission', permissionDirective);
}
